package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.OneSubject;
import com.atguigu.eduservice.entity.subject.SubjectData;
import com.atguigu.eduservice.entity.excel.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author hwt
 * @since 2022-08-21
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public R saveSubject(MultipartFile file, EduSubjectService subjectService) {

        try {
            // 获取文件输入流
            InputStream in = file.getInputStream() ;
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e) {
            System.err.println(e.getMessage());
        }

        return R.ok();
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {

        //查询所有一级分类 parent_id = 0
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        // 查询所有二级分类 parent_id!= 0
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperOne.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        // 一个自定义的封装方法，返回拼接好的数据
        return AssembleData(oneSubjectList,twoSubjectList) ;

    }

    private List<OneSubject> AssembleData(List<EduSubject> onSubject,List<EduSubject> twoSubject) {
        ArrayList<OneSubject> finalSubjectList = new ArrayList<>();

        // 增强 for 循环，获取到第一个一级 Subject
        for (EduSubject Subject : onSubject) {

            // 创建 vo 封装对象
            OneSubject oneSubject = new OneSubject(Subject.getId(),Subject.getTitle());

            // 将引用保存到集合中去
            finalSubjectList.add(oneSubject);

            // 遍历 二级 目录，查找 父id 等于 一级id 的，并保存到 oneSubject
            for (EduSubject eduSubject : twoSubject) {
                if (Subject.getId().equals(eduSubject.getParentId())) {
                    oneSubject.getChildren().add(new TwoSubject(eduSubject.getId(),eduSubject.getTitle()));
                }
            }
        }

        // 返回最终的 一级目录 ，和里面保存的子级目录
        return finalSubjectList;
    }
}








